#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <string.h>
#define FILENAME "log.txt"
int main()
{
    //int fd = open(FILENAME, O_RDONLY);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return 1;
    //}
    //dup2(fd, 0);
    //char buffer[1024];
    ////fread(buffer, 1, sizeof buffer, stdin);
    //read(fd, buffer, sizeof buffer);
    //printf("%s", buffer);

    int fd = open(FILENAME, O_CREAT|O_TRUNC|O_WRONLY, 0666);
    if(fd < 0)
    {
        perror("open");
        return 1;
    }
    dup2(fd, 1);
    printf("fd = %d", fd);

    //close(0);
    //int fd = open(FILENAME, O_RDONLY);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return 1;
    //}
    //char buffer[1024];
    ////fread(buffer, 1, sizeof buffer, stdin);
    //read(0, buffer, sizeof buffer);
    //printf("%s", buffer);


    //重定向写
    //close(1);
    //int fd = open(FILENAME, O_CREAT|O_TRUNC|O_WRONLY);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return 1;
    //}
    ////printf("fd = %d\n", fd);
    ////printf("stdout_fd = %d\n", stdout->_fileno);
    //fprintf(stdout, "fd = %d\n", fd);
    //fprintf(stdout, "stdout_fd = %d\n", stdout->_fileno);
    //fflush(stdout);
    //close(1);

    //fd的分配规则
    //close(0); //close(2);
    //int fd = open(FILENAME, O_CREAT|O_TRUNC|O_WRONLY, 0666);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return 1;
    //}
    //printf("fd = %d\n", fd);
    //close(fd);


    //0，1可以直接使用
    //char buffer[1024];
    //ssize_t s = read(0, buffer, 1024);
    //if(s > 0)
    //{
    //    buffer[s] = '\0';
    //    write(1, buffer, strlen(buffer));
    //}


    //1.正常打开
    //int fd = open(FILENAME, O_CREAT|O_WRONLY|O_TRUNC, 0666);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return -1;
    //}
    //printf("fd: %d\n", fd);
    //close(fd);



    //重定向写
    //close(1);
    //int fd = open(FILENAME, O_WRONLY|O_CREAT|O_TRUNC, 0666);
    //if(fd < 0)
    //{
    //    perror("open");
    //    return -1;
    //}

    //fprintf(stdout, "fd:%d\n", fd);
    //fprintf(stdout, "stdout->fd:%d\n", stdout->_fileno);

    //fd的分配规程
    //close(0); 
    //int fd = open(FILENAME, O_WRONLY|O_CREAT|O_TRUNC, 0666);
    //printf("fd:%d\n", fd);

    //可以直接使用0,1
    //char buffer[1024];
    //ssize_t sz = read(0, buffer, sizeof buffer);
    //if(sz > 0)
    //{
    //    buffer[sz] = '\0';
    //    write(1, buffer, sz + 1);
    //}
    return 0;
}
